package com.mall.mymall.config;

import com.mall.mymall.filter.JwtAuthenticationFilter;
import com.mall.mymall.service.AdministratorsService;
import com.mall.mymall.service.UsersService;
import com.mall.mymall.utils.JwtTokenProvider;
import com.mall.mymall.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig2 extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtTokenProvider jwtProvider;

    private AuthenticationManager authenticationManager = null;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UsersService usersService;

    @Autowired
    private AdministratorsService administratorsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        if (authenticationManager == null) {
            authenticationManager = authenticationManager();
        }
        http
                .csrf().disable() // 禁用CSRF保护
                .authorizeRequests()
                .antMatchers("/users/login"
                        , "/users/*"
                        , "/administrators/login"
                        , "/products/pageQuery"
                        , "/products/searchProduct"
                        , "/products/getAll"
                        , "/product/**"
                        , "/adminAvatar/**").permitAll() //放开拦截
                .anyRequest().authenticated() // 其他请求需要认证
                .and()
                .formLogin().disable() // 禁用默认的表单登录
                .httpBasic().disable()
                .addFilterBefore(new JwtAuthenticationFilter(jwtProvider, redisUtils, usersService, administratorsService),
                        SecurityContextPersistenceFilter.class);

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
